package com.one.blocks.rbac.controller;

import com.one.blocks.mvc.controller.AbstractController;
import com.one.blocks.mvc.response.ResponseHelper;
import com.one.blocks.mvc.response.WebResponse;
import com.one.blocks.rbac.controller.convert.SysAccountConvert;
import com.one.blocks.rbac.controller.query.SysAccountQuery;
import com.one.blocks.rbac.controller.vo.SysAccountLoginVo;
import com.one.blocks.rbac.controller.vo.SysAccountVo;
import com.one.blocks.rbac.domain.SysAccount;
import com.one.blocks.rbac.enums.RbacResponseEnum;
import com.one.blocks.rbac.manager.SysAccountManager;
import com.one.blocks.security.annotation.PreAuthorize;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;


/**
 * @author <a href="mailto:idler41@163.con">idler41</a> created on 2022-05-01 10:06:14
 */
@Api(tags = "系统登录账户接口")
@RestController
@RequestMapping("/system/account")
@Slf4j
@Validated
public class SysAccountController extends AbstractController<SysAccountManager, SysAccountConvert, SysAccount, SysAccountVo, SysAccountQuery> {

    @Autowired
    public SysAccountController(SysAccountManager manager) {
        super(manager, SysAccountConvert.INSTANCE);
    }

    @ApiOperation("根据用户名密码登录")
    @PostMapping(value = "/login", produces = MediaType.APPLICATION_JSON_VALUE)
    public WebResponse<Void> login(@Validated @RequestBody SysAccountLoginVo loginAccountVo, HttpServletRequest request, HttpServletResponse response) {
        SysAccount sysAccount = manager.loginByPassword(loginAccountVo, request, response);
        if (sysAccount != null) {
            return ResponseHelper.success();
        }
        return ResponseHelper.fail(RbacResponseEnum.INCORRECT_LOGIN_INFO);
    }

    @ApiOperation("用户登出")
    @PostMapping("/logout")
    public WebResponse<Void> logout(HttpServletRequest request) {
        manager.logout(request);
        return ResponseHelper.success();
    }

    @ApiOperation("查询指定指定用户的默认账户信息")
    @PreAuthorize("system:account:view")
    @GetMapping(value = "/user")
    public WebResponse<SysAccountVo> getByUserId(@Validated @NotNull @RequestParam Integer userId) {
        return ResponseHelper.success(convert.entityToVo(manager.getDefaultAccount(userId)));
    }
}